<template>
  <a-modal
    title="导入数据表"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height:90%;">

    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button @click="submitData" type="primary" :loading="btnLoading">导入</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <j-form-container>
        <a-form :form="form" slot="detail">
          <div class="basic-container" style="border-bottom:solid 0.3px #CCC;margin-bottom:20px;">
            <a-row>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据源">
                  <a-row :gutter="8">
                    <a-col :span="18">
                      <a-select show-search :disabled="dataSourceStopSelected" :loading="dataSourceStopSelected" :filter-option="filterOption" :getPopupContainer="trigger => trigger.parentNode" v-decorator="['code', { rules: [{ required: true, message: '请选择数据源'}] }]" placeholder="请选择数据源" @change="changeDataSource">
                        <a-select-option  :value="item.code" :key="item.code" v-for="item in dataSourceList">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="6">
                      <a-button class="atn-testbtn" type="primary"  style="width: 100%" @click="handleTest">测试</a-button>
                    </a-col>
                  </a-row>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据类型">
                  <a-radio-group v-model="dataType" v-decorator="['tableType', { initialValue: 1, rules: [{required: true}] }]" @change="changeDataType">
                    <a-radio :value="1">表</a-radio>
                    <a-radio :value="2">视图</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </a-form>
      </j-form-container>
      <div class="table-page-search-wrapper">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-item label="数据表名称" :labelCol="{span: 6}" :wrapperCol="{span: 14, offset: 1}">
              <a-input placeholder="请输入数据表名称" v-model="tableName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </div>
<!-- :scroll="tableHeight" -->
      <a-table
        ref="table"
        size="middle"
        :scroll="tableheight"
        bordered
        rowKey="tableName"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
          <template slot="tableComment" slot-scope="tableComment, record">
            <a-input v-if="selectedRowKeys.indexOf(record.tableName) != -1" @change="changeTableComment(record)" v-model="record.tableComment" />
            <span v-else>{{ tableComment }}</span>
          </template>
        </a-table>

      <!-- <a-table
        :scroll="tableHeight"
        :pagination="false"
        ref="table"
        size="middle"
        bordered
        rowKey="tableName"
        :columns="columns"
        :dataSource="dataSource"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap">
      </a-table> -->
    </a-spin>
  </a-modal>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, httpAction, postAction } from '@/api/manage'
export default {
  name: 'TransDb2Online',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      selectedRowTables: [],
      checkedDataSource: null,
      tableheight: { x: 1000, y: (document.body.clientHeight - (document.body.clientHeight > 450 ? 440 : 200)) },

      // tableHeight: { x: 1000, y: (document.body.clientHeight - (document.body.clientHeight > 650 ? 650 : 400)) },
      code: null,
      dataType: 1,
      dataSourceAll: [],
      form: this.$form.createForm(this),
      tableName: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      dataSourceList: [],
      modalWidth: 1200,
      visible: false,
      confirmLoading: false,
      btnLoading: false,
      dataSource: [],
      dataSourceStopSelected: false,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '表名',
          align: 'left',
          dataIndex: 'tableName'
        },
        {
          title: '备注',
          align: 'left',
          dataIndex: 'tableComment',
          scopedSlots: { customRender: 'tableComment' }
        }
      ],
      selectedRowKeys: []
    }
  },
  created() {
  },
  methods: {
    changeTableComment(record) {
      this.selectedRowTables.forEach(item => {
        if (item.tableName == record.tableName) {
          item.tableComment = record.tableComment
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleTest() {
      if (this.checkedDataSource == undefined || this.checkedDataSource == null) {
        this.$message.error('请选择数据源!')
        return
      }
      const loading = this.$message.loading('连接中……', 0)
      postAction('/stuationDataSource/testConnection', this.checkedDataSource).then(res => {
        if (res.success) {
          this.$message.success('连接成功')
        } else throw new Error(res.message)
      }).catch(error => {
        this.$warning({ title: '连接失败', content: error.message || error })
      }).finally(() => loading())
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination
      this.loadData()
    },
    searchQuery() {
      this.ipagination.total = 0
      this.ipagination.current = 1
      this.loadData()
    },
    changeDataType() {
      this.tableName = null
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.loadData()
    },
    getDataSourceList() {
      getAction('/sys/dataSource/list', { pageNo: 1, pageSize: 10000 }).then((res) => {
        if (res.success) {
          if (res.result.records != null) {
            this.dataSourceList = res.result.records.filter(item => item.dbStatus == '1')
          } else {
            this.dataSourceList = []
          }
        } else {
          this.dataSourceList = []
        }
      })
    },
    changeDataSource(val) {
      if (val == null || val == '') {
        this.checkedDataSource = null
      } else {
        this.checkedDataSource = this.dataSourceList.find(item => item.code == val)
      }

      if (val == null) {
        return
      }
      this.code = val
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.loadData()
    },
    loadData() {
      if (this.dataType == null || this.dataType == '' || this.code == null || this.code == '' || this.dataSourceStopSelected) {
        return
      }
      this.dataSourceAll = []
      this.dataSource = []
      this.dataSourceStopSelected = true
      getAction('/dataSource/scSituationTable/tables', { tableName: this.tableName, pageNo: this.ipagination.current, pageSize: this.ipagination.pageSize, code: this.code, tableType: this.dataType }).then((res) => {
        if (res.success && res.result != '未查询到数据') {
          this.ipagination.total = res.result.total
          const recordsTemp = res.result.records
          recordsTemp.forEach(item => {
            const selectedRecord = this.selectedRowTables.find(item1 => item1.tableName == item.tableName)
            if (selectedRecord != undefined && selectedRecord != null) {
              item.tableComment = selectedRecord.tableComment
            }
          })

          this.dataSource = res.result.records
        } else {
          this.ipagination.total = 0
          this.dataSource = []
        }
      }).finally(() => {
        this.dataSourceStopSelected = false
      })
    },
    show() {
      this.getDataSourceList()
      this.visible = true
      this.btnLoading = false
      this.selectedRowKeys = []
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRowTables = selectedRows
    },
    onClearSelected() {
      this.selectedRowTables = []
      this.selectedRowKeys = []
    },
    resetForm() {
      this.form.resetFields()
      this.tableName = null
      this.dataSource = []
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.code = null
      this.selectedRowTables = []
      this.selectedRowKeys = []
    },
    handleCancel() {
      this.resetForm()
      this.visible = false
    },
    submitData() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const formData = values
          if (this.selectedRowKeys == null || this.selectedRowKeys.length == 0) {
            this.$message.error('请选择数据表!')
            return
          }
          const tableDto = {}
          this.selectedRowTables.forEach(item => {
            tableDto[item.tableName] = item.tableComment
          })
          formData.tableNames = this.selectedRowKeys
          this.btnLoading = true
          httpAction('/dataSource/scSituationTable/saveTableList?code=' + formData.code + '&tableType=' + formData.tableType, tableDto, 'PUT').then((res) => {
            this.btnLoading = false
            if (res.success) {
              this.$message.success('保存成功!')
              this.resetForm()
              this.visible = false
              this.$emit('ok')
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    }
  }
}
</script>
